import {
    Component,
    EventTouch,
    ImageAsset, Label,
    Node,
    Sprite, SpriteFrame,
    Vec3,
    _decorator,
    assetManager,
    native,
    resources,
    EventTarget,
    color,
    UITransform,
    Button
} from 'cc';
import { removeToucheEvent } from '../../common/Utils';
import Global from '../../common/Global';
const { ccclass, property } = _decorator;
// 电影票数据结构
export default interface TicketItem {
    sysVideoId: number,
    canWatch: number, // 是否可以观看，0否，1是
    originalFilename: string, // 原始文件名
    url: string, // 文件外链
    price: number, // 视频价格-达芬奇币
    presignedUrl: string, // 视频首帧
    progress: string, // 观看进度
    updateTime: string
}
export const movieEventTarget = new EventTarget();

@ccclass('TicketTemplate')
export class TicketTemplate extends Component {
    @property(Sprite)
    videoBg: Sprite | null = null;

    @property(Label)
    fileName: Label | null = null;

    @property(Label)
    date: Label | null = null;

    @property(Node)
    bgBox: Node | null = null;
    
    movieData: TicketItem | null = null;
    index: number = 0
    protected onLoad(): void {
        // 监听自定义事件
        movieEventTarget.on('videoProgress', this.handleVideoProgress, this);
    }

    handleVideoProgress(progress: string) {
        // 在这里进行相关的 UI 更新或其他逻辑
        if (this.movieData) {
            this.movieData.progress = progress
            native?.bridge?.sendToNative('log.e', 'jsb receive videoProgress progress = ' + progress);
            native?.bridge?.sendToNative('log.e', 'jsb this.movieData.progress = ' + this.movieData.progress);
        }
    }

    start() {

    }

    update(deltaTime: number) {

    }

    protected onEnable(): void {
        this.bindPlayAnimation();
    }
    protected onDisable(): void {
        removeToucheEvent(this.node);
    }
    // 初始化ticket，更换ticket背景
    init(data: TicketItem, index: number) {
        native?.bridge?.sendToNative('log.e', 'init data.progress = ' + data.progress);
        this.index = index;
        this.movieData = data;
        this.node.name = data?.url?.replace(/\//g, "");
        // 加载一个远程图片
        assetManager.loadRemote(data?.presignedUrl, {
            ext: '.png',
            cacheEnabled: true
        }, (err: Error | null, asset: ImageAsset) => {
            if (err) {
                console.error(err);
                return;
            }
            this.videoBg.getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(asset);
        });
        
        let nameArr = data?.originalFilename?.split("/");
        let name = nameArr[nameArr?.length - 1];
        this.fileName.string = name?.replace(".mp4", "");
        this.date.string = data?.updateTime;
        let idx = index % 4;
        let bg = this.bgBox.getChildByName(`T${idx + 1}`).getComponent(Sprite).spriteFrame;
        let pBg = this.bgBox.getChildByName(`Pressed${idx + 1}`).getComponent(Sprite).spriteFrame;

        this.node.getComponent(Sprite).spriteFrame = bg;

        this.node.getComponent(Button).normalSprite = bg;
        this.node.getComponent(Button).pressedSprite = pBg;

    }
    // 播放回调
    onSceneLaunched(event: EventTouch) {
        // 获取触摸点信息
        let touch = event.touch;
        let location = touch.getLocation(); // 获取触点在按钮节点上的位置

        // 输出触点信息，例如位置
        console.log("Touch Start at: ", location);
    }
    // 播放按钮动画
    bindPlayAnimation() {
        this.node?.on(Node.EventType.TOUCH_START, this.onPlayTouchStart, this);
        this.node?.on(Node.EventType.TOUCH_END, this.onPlayTouchEnd, this);
        this.node?.on(Node.EventType.TOUCH_MOVE, this.onPlayTouchMove, this);
        this.node?.on(Node.EventType.TOUCH_CANCEL, this.onPlayTouchCancel, this);
        this.node?.children?.map(child => {
            removeToucheEvent(child);
        })
    }

    onPlayTouchStart(e: EventTouch) {
    }
    onPlayTouchMove(e: EventTouch) {
    }

    onPlayTouchEnd(e: EventTouch) {
        console.log("onPlayTouchEnd ===== e.getID():%s", e.getID());
        if (Global.ticketTouchId !== null) return;
        Global.ticketTouchId = e.getID();
        e.propagationStopped = true;
        this.node.getComponent(Sprite).color = color("#FFFFFFFF");
        console.log('log.e send openVideo this.movieData.originalFilename=%s, this.movieData.progress =%s ', this.movieData.originalFilename, this.movieData.progress);
        native?.bridge?.sendToNative('log.e', 'send openVideo this.movieData.progress = ' + this.movieData.progress);
        native?.bridge?.sendToNative('openVideo', JSON.stringify(this.movieData));
    }
    
    onPlayTouchCancel(e: EventTouch) {
    }
}


